<script>
export default {
  name: "Recruitment-application.vue"
}
</script>

<template>
  <div class="recruitment-application">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>活动报名</span>
        </div>
      </template>
      
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
          v-model="searchQuery"
          placeholder="搜索活动名称"
          class="search-input"
          clearable
          @clear="handleSearch"
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>

      <!-- 活动列表 -->
      <el-table :data="filteredActivities" style="width: 100%" v-loading="loading">
        <el-table-column prop="clubName" label="社团名称" width="180">
          <template #default="scope">
            {{ scope.row.clubName || '未知社团' }}
          </template>
        </el-table-column>
        <el-table-column prop="title" label="活动名称" width="180" />
        <el-table-column prop="descr" label="活动描述" />
        <el-table-column prop="activityType" label="活动类型" width="120" />
        <el-table-column prop="location" label="活动地点" width="180" />
        <el-table-column prop="startTime" label="开始时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="endTime" label="结束时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="handleApply(scope.row)"
              :disabled="!isActivityOpen(scope.row) || scope.row.applicationStatus"
            >
              {{ getButtonText(scope.row) }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 报名表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="活动报名"
      width="50%"
    >
      <el-form :model="applicationForm" label-width="120px">
        <el-form-item label="姓名">
          <el-input v-model="applicationForm.name" disabled />
        </el-form-item>
        <el-form-item label="学号">
          <el-input v-model="applicationForm.studentId" disabled />
        </el-form-item>
        <el-form-item label="联系方式">
          <el-input v-model="applicationForm.contact" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="applicationForm.remark"
            type="textarea"
            :rows="4"
            placeholder="请输入备注信息（选填）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitApplication">
            确认报名
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

// 数据
const activities = ref([])
const loading = ref(false)
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dialogVisible = ref(false)
const currentActivity = ref(null)
const studentClubIds = ref([]) // 存储学生已加入的社团ID列表

// 报名表单
const applicationForm = ref({
  name: '',
  studentId: '',
  contact: '',
  remark: ''
})

// 过滤后的活动列表
const filteredActivities = computed(() => {
  return activities.value.filter(activity =>
    activity?.title?.toLowerCase().includes(searchQuery.value.toLowerCase()) ?? false
  )
})

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString()
}

// 获取学生已加入的社团列表
const fetchStudentClubs = async (studentId) => {
  try {
    const response = await request.get(`/club/selectByStudentId/${studentId}`)
    if (response.code === '200' && Array.isArray(response.data)) {
      studentClubIds.value = response.data.map(club => club.id)
      return true
    }
    return false
  } catch (error) {
    console.error('获取学生社团信息失败:', error)
    return false
  }
}

// 获取活动列表
const fetchActivities = async () => {
  loading.value = true
  console.log('开始获取活动列表...')
  try {
    const user = JSON.parse(localStorage.getItem('xm-pro-user'))
    if (!user || user.role !== 'STU') {
      console.error('User is not a student or not logged in.')
      ElMessage.error('请先登录学生账号')
      loading.value = false
      return
    }

    // 1. 获取学生已加入的社团列表
    const hasClubs = await fetchStudentClubs(user.id)
    if (!hasClubs) {
      ElMessage.warning('您还没有加入任何社团，请先加入社团')
      activities.value = []
      total.value = 0
      loading.value = false
      return
    }

    // 2. 获取所有活动信息
    const activityRes = await request.get('/activity/selectAll')
    if (activityRes.code === '200') {
      // 只显示学生已加入社团的活动信息
      const allActivities = activityRes.data || []
      activities.value = allActivities.filter(activity => 
        studentClubIds.value.includes(activity.clubId)
      )
      total.value = activities.value.length
    } else {
      ElMessage.error(activityRes.msg || '获取活动列表失败')
    }
  } catch (error) {
    console.error('获取数据失败，错误详情:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 检查活动是否开放
const isActivityOpen = (activity) => {
  // 如果学生不是该社团成员，直接返回false
  if (!studentClubIds.value.includes(activity.clubId)) {
    return false
  }

  const now = new Date()
  const startTime = new Date(activity.startTime)
  const endTime = new Date(activity.endTime)
  return now >= startTime && now <= endTime
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchActivities(); // 恢复调用 fetchActivities
};

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchActivities(); // 恢复调用 fetchActivities
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchActivities(); // 恢复调用 fetchActivities
};

// 处理报名
const handleApply = (activity) => {
  // 如果学生不是该社团成员，不允许报名
  if (!studentClubIds.value.includes(activity.clubId)) {
    ElMessage.warning('您不是该社团成员，无法报名活动')
    return
  }

  currentActivity.value = activity
  // 获取当前用户信息
  const user = JSON.parse(localStorage.getItem('xm-pro-user'))
  applicationForm.value = {
    name: user.name,
    studentId: user.studentId,
    contact: '',
    remark: '',
    activityId: activity.id
  }
  dialogVisible.value = true
}

// 提交报名
const submitApplication = async () => {
  if (!applicationForm.value.contact) {
    ElMessage.error('请输入联系方式')
    return
  }
  if (!applicationForm.value.remark) {
    ElMessage.error('请输入备注信息')
    return
  }

  try {
    const user = JSON.parse(localStorage.getItem('xm-pro-user'))
    const response = await request.post('/activityapplication/add', {
      activityId: applicationForm.value.activityId,
      studentId: user.id,
      contact: applicationForm.value.contact,
      remark: applicationForm.value.remark,
      status: '待审核'
    })
    
    if (response.code === '200') {
      ElMessage.success('报名成功，请等待审核')
      dialogVisible.value = false
      
      // 更新当前活动的报名状态
      const activity = activities.value.find(a => a.id === applicationForm.value.activityId)
      if (activity) {
        activity.applicationStatus = '待审核'
      }
      
      // 重新获取活动列表以更新所有状态
      await fetchActivities()
    } else {
      ElMessage.error(response.msg || '报名失败')
    }
  } catch (error) {
    console.error('报名失败:', error)
    ElMessage.error('报名失败')
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchActivities()
})

// 获取按钮文本
const getButtonText = (activity) => {
  if (activity.applicationStatus === '已通过') {
    return '已报名'
  } else if (activity.applicationStatus === '待审核') {
    return '审核中'
  } else if (activity.applicationStatus === '已拒绝') {
    return '已拒绝'
  } else if (!isActivityOpen(activity)) {
    return '已结束'
  } else {
    return '报名'
  }
}
</script>

<style scoped>
.recruitment-application {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>